<template>
	<view class="car-allocate-container flat-page">
		<!-- 1. 顶部导航栏 -->
		<view class="flat-nav">
			<image src="/static/icons/back.png" class="back-icon" mode="aspectFit" @click="goBack" />
			<text class="nav-title">{{mode === 'edit' ? '编辑车辆' : '添加车辆'}}</text>
			<view class="nav-placeholder"></view>
		</view>

		<!-- 2. 表单区域 -->
		<view class="form-container">
			<!-- 车牌号 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">车牌号 <text class="required">*</text></text>
				</view>
				<input class="input" v-model="vehicle.licensePlate" :disabled="!isEditable"
					placeholder="请输入车牌号，如：沪A12345" />
			</view>

			<!-- 车辆类型 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">车辆类型 <text class="required">*</text></text>
				</view>
				<picker mode="selector" :range="vehicleTypeOptions" @change="onVehicleTypeChange" @click.prevent>
					<view class="picker-val">{{ selectedVehicleTypeText || '请选择车辆类型' }}</view>
				</picker>
			</view>

			<!-- 核载人数 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">核载人数 <text class="required">*</text></text>
				</view>
				<input class="input" v-model.number="vehicle.loadCapacity" type="number" :disabled="!isEditable"
					placeholder="请输入核载人数" 
					min="1"
					max="99"
					@input="validateLoadCapacity"/>
				<text class="error-text" v-if="loadCapacityError">{{loadCapacityError}}</text>
			</view>

			<!-- 车辆状态 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">车辆状态 <text class="required">*</text></text>
				</view>
				<picker mode="selector" :range="statusOptions" @change="onStatusChange" @click.prevent>
					<view class="picker-val">{{ selectedStatusText || '请选择车辆状态' }}</view>
				</picker>
			</view>

			<!-- 司机姓名 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">司机姓名</text>
				</view>
				<input class="input" v-model="vehicle.driverName" :disabled="!isEditable" placeholder="请输入司机姓名（可选）" />
			</view>

			<!-- 司机电话 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">司机电话</text>
				</view>
				<input class="input" v-model="vehicle.driverPhone" :disabled="!isEditable" placeholder="请输入司机电话（可选）" />
			</view>

			<!-- 备注信息 -->
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">备注信息</text>
				</view>
				<textarea class="textarea" v-model="vehicle.remark" :disabled="!isEditable"
					placeholder="请输入备注信息"></textarea>
			</view>

			<!-- 为底部按钮留出空间 -->
			<view style="height: 150rpx;"></view>
		</view>

		<!-- 3. 底部固定保存按钮（始终显示） -->
		<view class="save-bottom-btn">
			<button @click="saveVehicle" class="save-button" :disabled="isSubmitting">保存</button>
		</view>
	</view>
</template>

<script>
	import { createVehicle, updateVehicle, getVehicleById } from '@/https/vehicle.js';
	export default {
		// 数据部分
		data() {
			return {
				// 车辆状态常量
				VEHICLE_STATUS: {
					AVAILABLE: 0, // 可用
					MAINTENANCE: 1, // 维修中
					DISABLED: 2 // 已停用
				},

				// 车辆数据
				vehicle: {
					vehicleId: '',
					licensePlate: '',
					vehicleType: '',
					loadCapacity: 0,
					status: 0, // 默认可用
					driverName: '',
					driverPhone: '',
					remark: ''
				},

				// 表单错误信息
				loadCapacityError: '',

				// 提交状态，防止重复提交
				isSubmitting: false,

				// 页面模式: 'add' | 'edit'
				mode: 'add',

				// 车辆类型数据
				vehicleTypes: [
					{ label: '大巴', value: '大巴' },
					{ label: '中巴', value: '中巴' },
					{ label: '轿车', value: '轿车' },
					{ label: '商务车', value: '商务车' },
					{ label: '其他', value: '其他' }
				],

				// 车辆类型选项 - 用于picker显示
				vehicleTypeOptions: ['大巴', '中巴', '轿车', '商务车', '其他'],

				// 车辆状态选项 - 用于picker显示
				statusOptions: ['可用', '维修中', '已停用']
			};
		},

		// 计算属性
		computed: {
			// 计算当前选中的车辆类型文本
			selectedVehicleTypeText() {
				if (!this.vehicle.vehicleType) return '';
				const selectedType = this.vehicleTypes.find(type => type.value === this.vehicle.vehicleType);
				return selectedType ? selectedType.label : '';
			},

			// 计算当前选中的状态文本
			selectedStatusText() {
				const statusIndex = this.vehicle.status;
				return this.statusOptions[statusIndex] || '';
			},

			// 页面编辑状态，始终可编辑
			isEditable() {
				return true;
			}
		},

		// 生命周期钩子
		onLoad(options) {
			// 安全地获取id参数，并转换为数字类型
			const id = options?.id && options.id !== '' ? parseInt(options.id) : 0;

			// 判断是否为编辑模式
			this.mode = id !== 0 && !isNaN(id) && id > 0 ? 'edit' : 'add';

			// 加载车辆数据
			this.loadVehicleData();
		},

		// 方法部分
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 验证核载人数
			validateLoadCapacity() {
				const capacity = this.vehicle.loadCapacity;
				if (!capacity) {
					this.loadCapacityError = '请输入核载人数';
					return;
				}
				
				if (capacity < 1) {
					this.loadCapacityError = '核载人数不能小于1';
				} else if (capacity > 99) {
					this.loadCapacityError = '核载人数不能大于99';
				} else {
					this.loadCapacityError = '';
				}
			},

			// 处理车辆类型选择变化
			onVehicleTypeChange(e) {
				if (!this.isEditable) return;
				const index = e.detail.value;
				this.vehicle.vehicleType = this.vehicleTypes[index].value;
			},

			// 处理车辆状态选择变化
			onStatusChange(e) {
				if (!this.isEditable) return;
				const index = e.detail.value;
				this.vehicle.status = parseInt(index);
			},

			// 加载车辆数据
			loadVehicleData() {
				// 获取页面参数
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				
				// 安全地获取id参数，并转换为数字类型
				const id = currentPage.options?.id && currentPage.options.id !== '' ? parseInt(currentPage.options.id) : 0;

				if (id) {
					// 有 id 的情况，加载数据（编辑模式）
					try {
						uni.showLoading({
							title: '加载中...'
						});

						// 这里使用Promise来模拟异步操作
						getVehicleById(id).then(vehicleData => {
							// 检查返回数据结构
							if (vehicleData && vehicleData.vehicleId !== undefined) {
								// 适配API返回的数据结构
								this.vehicle = {
									vehicleId: vehicleData.vehicleId,
									licensePlate: vehicleData.licensePlate || '',
									vehicleType: vehicleData.vehicleType || '',
									loadCapacity: vehicleData.loadCapacity || 0,
									status: vehicleData.status !== undefined ? vehicleData.status : this.VEHICLE_STATUS.AVAILABLE,
									driverName: vehicleData.driverName || '',
									driverPhone: vehicleData.driverPhone || '',
									remark: vehicleData.remark || ''
								};
							} else {
								uni.showToast({
									title: '未找到车辆信息',
									icon: 'none'
								});
								// 延迟返回，让用户看到提示
								setTimeout(() => {
									this.goBack();
								}, 1500);
							}
						})
						.catch(error => {
							console.error('获取车辆数据失败:', error);
							uni.showToast({
								title: '加载失败，请重试',
								icon: 'none'
							});
						})
						.finally(() => {
							uni.hideLoading();
							// 无论成功失败，都重置提交状态
							this.isSubmitting = false;
						});
					} catch (error) {
						console.error('加载车辆数据异常:', error);
						uni.hideLoading();
						this.isSubmitting = false;
					}
				} else {
					// 新增模式，重置数据并确保模式为 add
					this.mode = 'add';
					this.vehicle = {
						vehicleId: 0,
						licensePlate: '',
						vehicleType: '',
						loadCapacity: 0,
						status: this.VEHICLE_STATUS.AVAILABLE,
						driverName: '',
						driverPhone: '',
						remark: ''
					};
				}
			},

			// 保存车辆信息
			saveVehicle() {
				// 防止重复提交
				if (this.isSubmitting) {
					return;
				}

				// 表单验证
				if (!this.vehicle.licensePlate) {
					uni.showToast({
						title: '请输入车牌号',
						icon: 'none'
					});
					return;
				}

				if (!this.vehicle.vehicleType) {
					uni.showToast({
						title: '请选择车辆类型',
						icon: 'none'
					});
					return;
				}

				if (!this.vehicle.loadCapacity || this.vehicle.loadCapacity <= 0) {
					uni.showToast({
						title: '请输入有效的核载人数',
						icon: 'none'
					});
					return;
				}

				// 设置提交状态为true
				this.isSubmitting = true;

				// 构建请求参数
				const requestData = {
					vehicleId: this.vehicle.vehicleId || 0,
					openId: null, // 可以根据需求设置
					licensePlate: this.vehicle.licensePlate,
					vehicleType: this.vehicle.vehicleType,
					loadCapacity: this.vehicle.loadCapacity,
					status: this.vehicle.status,
					driverName: this.vehicle.driverName || null,
					driverPhone: this.vehicle.driverPhone || null,
					remark: this.vehicle.remark || ''
				};

				try {
					// 显示加载提示
					uni.showLoading({
						title: this.vehicle.vehicleId ? '更新中...' : '保存中...'
					});

					// 根据模式选择API
					const apiCall = this.vehicle.vehicleId ? 
						updateVehicle(requestData) : 
						createVehicle(requestData);

					// 调用API
					apiCall.then(() => {
						uni.showToast({
							title: this.vehicle.vehicleId ? '编辑成功' : '添加成功',
							icon: 'success',
							complete: () => {
								// 延迟返回，让用户看到成功提示
								setTimeout(() => {
									this.goBack();
								}, 1500);
							}
						});
					})
					.catch(error => {
						console.error('保存车辆信息失败:', error);
						uni.showToast({
							title: this.vehicle.vehicleId ? '编辑失败' : '添加失败',
							icon: 'none',
							duration: 2000
						});
					})
					.finally(() => {
						uni.hideLoading();
						this.isSubmitting = false;
					});
				} catch (error) {
					console.error('保存车辆信息异常:', error);
					uni.hideLoading();
					this.isSubmitting = false;
				}
			}
		}
	};
</script>

<style scoped>
	/* 全局基础样式 */
	.flat-page {
		background-color: #f5f7fa;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 导航栏样式 */
	.flat-nav {
		background-color: #2c6ecb;
		padding: 30rpx 20rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
		position: sticky;
		top: 0;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.back-icon {
		width: 32rpx;
		height: 32rpx;
		touch-action: manipulation;
	}

	.nav-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #fff;
		flex: 1;
		text-align: center;
	}

	.nav-placeholder {
		width: 32rpx;
		height: 32rpx;
	}

	/* 表单区域 */
	.form-container {
		padding: 30rpx;
		padding-top: 20rpx;
	}

	/* 表单项目 - 保留用于兼容 */
	.form-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 25rpx 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 表单标签 */
	.label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
		font-weight: 500;
	}

	/* 必填项标记 */
	.required {
		color: #f00;
	}

	/* 输入框 */
	.input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		padding: 10rpx 0;
		text-align: right;
	}

	/* 错误提示文本 */
	.error-text {
		flex: 1;
		font-size: 24rpx;
		color: #f5222d;
		margin-top: 10rpx;
		text-align: right;
	}

	/* 表单行样式 */
	.form-row {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 25rpx 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 标签包装 */
	.label-wrap {
		flex: 0 0 180rpx;
	}

	/* 选择器样式 */
	.picker-val {
		flex: 1;
		font-size: 28rpx;
		color: #666;
		text-align: right;
		padding: 10rpx 0;
	}
	
	/* 处理picker的默认样式 */
	:deep(.uni-picker) {
		flex: 1;
	}
	
	:deep(.uni-picker__placeholder) {
		font-size: 28rpx !important;
		color: #666 !important;
	}
	
	:deep(.uni-picker__value) {
		font-size: 28rpx !important;
		color: #333 !important;
	}

	/* 文本域 */
	.textarea {
		flex: 1;
		height: 200rpx;
		font-size: 28rpx;
		color: #333;
		border: none;
		resize: none;
		padding: 10rpx 0;
		text-align: right;
	}

	/* 保存按钮 - 放在页面底部固定位置 */
	.save-bottom-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #eee;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.save-button {
		background-color: #007aff;
		color: #fff;
		text-align: center;
		padding: 25rpx;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: 500;
		width: 100%;
		border: none;
	}

	.save-button:active {
		opacity: 0.8;
	}

	.save-button[disabled] {
		background-color: #a0a0a0;
		opacity: 0.7;
	}
</style>